package com.ruoyi.web.config.mybatisplus;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.ruoyi.common.utils.SecurityUtils;

/**
 * 自动填充审计信息
 * 
 * @author lincm
 * @date 2022/11/11
 */
@Component
public class AuditMetaObjectHandler implements MetaObjectHandler {

    private final static String CREATE_TIME = "createTime";
    private final static String CREATE_BY = "createBy";
    private final static String UPDATE_TIME = "updateTime";
    private final static String UPDATE_BY = "updateBy";
    // private final static String DEL_FLAG = "delFlag";

    /**
     * 不处理createUser，updateUser的表
     */
    public static final List<String> IGNORE_TABEL =
        new ArrayList<>(Arrays.asList("sys_logininfor", "sys_oper_log", "sys_user", "cli_sms_record"));

    @Override
    public void insertFill(MetaObject metaObject) {
        boolean createDate = metaObject.hasSetter(CREATE_TIME);
        boolean updateDate = metaObject.hasSetter(UPDATE_TIME);
        if (createDate || updateDate) {
            LocalDateTime now = LocalDateTime.now();
            if (createDate) {
                this.setFieldValByName(CREATE_TIME, now, metaObject);
            }
            if (updateDate) {
                this.setFieldValByName(UPDATE_TIME, now, metaObject);
            }
        }
        TableInfo tableInfo = findTableInfo(metaObject);
        if (!IGNORE_TABEL.contains(tableInfo.getTableName())) {
            if (metaObject.hasSetter(CREATE_BY)) {
                this.setFieldValByName(CREATE_BY, String.valueOf(SecurityUtils.getLoginUser().getUserId()), metaObject);
            }
            if (metaObject.hasSetter(UPDATE_BY)) {
                this.setFieldValByName(UPDATE_BY, String.valueOf(SecurityUtils.getLoginUser().getUserId()), metaObject);
            }
        }
        // 删除标识
        // strictInsertFill(metaObject, DEL_FLAG, Integer.class, 5);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasSetter(UPDATE_TIME)) {
            this.setFieldValByName(UPDATE_TIME, LocalDateTime.now(), metaObject);
        }
        TableInfo tableInfo = findTableInfo(metaObject);
        if (!IGNORE_TABEL.contains(tableInfo.getTableName())) {
            if (metaObject.hasSetter(UPDATE_BY)) {
                this.setFieldValByName(UPDATE_BY, String.valueOf(SecurityUtils.getLoginUser().getUserId()), metaObject);
            }
        }
    }
}